<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/31/24
 * Time: 3:19 PM
 */

namespace app\adminapi\logic\risk_report;

use app\common\logic\BaseLogic;
use app\common\model\auth\Admin;
use app\common\model\media\MediaCreative;
use app\common\model\media_account\MediaAccount;
use app\common\model\risk_report\RiskReport;


class ReportLogic extends BaseLogic
{
    /**
     * 获取小时报表
     *
     * @param $promotionLinkId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getHourReport($promotionLinkId, $date, $filterCharge)
    {
        $list = RiskReport::where('promotion_link_id', $promotionLinkId)->where('count_date', $date)->order('hour', 'asc')->select();
        foreach ($list as &$item) {
            $item->hour = $item->hour . '点';

            $item->add_up_recycle_rate = getRate($item->add_up_recharge_money, $item->cost_money); // 累计回收率
            $item->roi                 = getRate($item->new_fans_recharge_money, $item->cost_money);  // 首日回收roi
            $item->add_desktop_cost    = getDiv($item->cost_money, $item->add_desktop_num);    // 加桌成本
            $item->new_fans_pay_price  = getDiv($item->cost_momey, $item->new_fans_pay_num); // 付费新粉单价

            // 素材
            $item->creative        = $this->getCreative($item->promotion_link_id, $filterCharge);
            $item->pitcher_name    = Admin::where('id', $item->pitcher_id)->value('name') ?? '';
            $item->advertiser_name = MediaAccount::where('advertiser_id', $item->advertiser_id)->value('advertiser_name') ?? '';
        }

        return $list->toArray();
    }


    /**
     * 获取创意封面
     *
     * @param $linkId
     * @return array
     */
    public function getCreative($linkId, $filterCharge)
    {
        $creativeArr = MediaCreative::where('promotion_link_id', $linkId)
            ->field('unit_id, cover_image_urls, video_urls, charge, show, photo_click, play_3s_ratio, block, negative')
            ->where('charge', '>=', $filterCharge)
            ->select()
            ->toArray();
        $result      = [];
        foreach ($creativeArr as $item) {
            $result[] = [
                'covers'        => explode(',', $item['cover_image_urls']),
                'videos'        => explode(',', $item['video_urls']),
                'charge'        => $item['charge'],
                'show'          => $item['show'],
                'photo_click'   => $item['photo_click'],
                'play_3s_ratio' => ($item['play_3s_ratio'] * 100) . '%',
                'block'         => $item['block'],
                'negative'      => $item['negative'],
            ];
        }

        return $result;
    }
}
